<?php
/**
 * Created by Adu at 2020/4/10
 */

namespace backend\models\c2\form;


use common\models\c2\entity\Product;
use common\models\c2\entity\ProductPackage;
use common\models\c2\entity\ProductSku;
use common\models\c2\entity\ProductSkuAssemble;
use kzo\base\models\ModelTrait;
use Yii;
use yii\base\Model;
use yii\validators\RequiredValidator;

class ProductPackageForm extends Model
{

    use ModelTrait;

    public $items;
    /**
     * @var Product
     */
    public $entityModel;

    public function rules()
    {
        return [
            [['items', 'created_at', 'updated_at'], 'safe'],
            [['items'], 'validateItems'],
        ]; // TODO: Change the autogenerated stub
    }

    public function validateItems($attribute)
    {
        $requiredValidator = new RequiredValidator();
        foreach ($this->$attribute as $index => $row) {
            $error = null;
            $requiredValidator->validate($row['package_id'], $error);
            if (!empty($error)) {
                $key = $attribute . '[' . $index . '][package_id]';
                $this->addError($key, Yii::t('app.c2', '{attribute} can not be empty!', ['attribute' => Yii::t('app.c2', 'Product')]));
            }
        }
    }

    public function loadItems()
    {
        $this->items = $this->entityModel->getPackages()->all();
    }


    public function loadDefaultValues($skipIfSet = true)
    {

    }

    public function save()
    {
        if (!empty($this->items)) {
            $product_id = $this->entityModel->id;
            foreach ($this->items as $item) {
                $attributes = [
                    'label' => isset($item['label']) ? $item['label'] : '',
                    'package_id' => isset($item['package_id']) ? $item['package_id'] : 0,
                    'product_id' => $product_id,
                    'num' => isset($item['num']) ? $item['num'] : 0,
                    'capacity' => isset($item['capacity']) ? $item['capacity'] : 0,
                    'position' => isset($item['position']) ? $item['position'] : 0,
                ];

                if (isset($item['id']) && $item['id'] == '') {
                    $itemModel = new ProductPackage();
                    $itemModel->setAttributes($attributes);
                    $itemModel->link('owner', $this->entityModel);
                } else {
                    $itemModel = ProductPackage::findOne($item['id']);
                    if (!is_null($itemModel)) {
                        $itemModel->updateAttributes($attributes);
                    }
                }
            }
        }
        return true;
    }

}